package com.qf.controller;

import com.qf.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author fy
 * @version V1.0
 * @Project day41
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/5/27 13:06
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1:获取请求参数（标识符，方法名）
        String methodStr = req.getParameter(Constants.TAG);

        //2：如果method没有获取到值，我们就跳转到首页
        if(methodStr == null || "".equals(methodStr)){
            methodStr = Constants.INDEX;
        }
        //3：反射调用对应的业务逻辑方法
        //获取class类
        Class clazz = this.getClass();


        try {
            //4：从类中获取方法对象
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //5.执行从类中获取到的方法对象，接收方法执行结果
//            Object result = method.invoke(this, req, resp);
            Object result = method.invoke(this, req, resp);
            //6:根据返回的结果进行判断。
            if (result != null){
                //jump获取到后例如："redirect:http://localhost:8080/admin/admin.jsp"
                String jump = (String)result;

                if (jump.startsWith(Constants.FORWARD)){
                    //7：判断执行后是请求转发处理
                    //获取路径，例如：http://localhost:8080/admin/admin.jsp
                    //字符串截取
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    req.getRequestDispatcher(path).forward(req, resp);
                }else if (jump.startsWith(Constants.REDIRECT)){
                    //8：判断执行后是重定向处理
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    //执行重定向
                    resp.sendRedirect(path);

                }else{
                    //其他类型的返回
                    resp.getWriter().println(jump);

                }

            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
